package com.cb.domain.dao.user.impl;

 
 import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.cb.core.dao.hibernate.GenericDAOHibernate;
import com.cb.domain.model.system.SystemUser;
import com.cb.domain.model.user.UserAccount;

 public class UserDetailsServiceImpl extends GenericDAOHibernate<UserAccount, Long> implements
 		UserDetailsService{
 	public UserDetailsServiceImpl() {
 		super(UserAccount.class);
 	}

 	@SuppressWarnings("deprecation")
 	public UserDetails loadUserByUsername(final String username)
 			throws UsernameNotFoundException, DataAccessException {
 		try {
 			return (UserDetails) getHibernateTemplate().execute(
 					new HibernateCallback() {
 						public Object doInHibernate(Session session) {
 							String hql = "from UserAccount where username=?";
 							Query queryObject = session.createQuery(hql);
 							SessionFactoryUtils.applyTransactionTimeout(
 									queryObject, session.getSessionFactory());
 							queryObject.setParameter(0, username);
 							System.out.println("username===="+username);
 							UserAccount user = (UserAccount) queryObject.uniqueResult();
 							// 加载该用户的权限
 							if (user != null) {
 								Hibernate.initialize(user.getRoles());
 								return user;
 							} else {
 								String hqlFindAdmin = "from SystemUser where userName=?";
 								Query queryObjectFindAdmin = session
 										.createQuery(hqlFindAdmin);
 								SessionFactoryUtils.applyTransactionTimeout(
 										queryObjectFindAdmin, session
 												.getSessionFactory());
 								queryObjectFindAdmin.setParameter(0, username);
 								SystemUser adminUser = (SystemUser) queryObjectFindAdmin
 										.uniqueResult();
 								// 加载该用户的权限
 								if (adminUser != null) {
 									Hibernate.initialize(adminUser.getRoles());
 								}
 								return adminUser;
 							}
 						}
 					}, true);
 		} catch (Exception e) {
 			throw new UsernameNotFoundException("user '" + username
 					+ "' not found...", e);
 		}
 	}
 }


